package com.glela.platform.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.exception.VersionNotFoundException;
import com.glela.platform.mapper.VersionMapper;
import com.glela.platform.model.request.RequestVersionModel;
import com.glela.platform.model.response.ResponseVersion;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.VersionService;

@Service("VersionServiceImpl")
public class VersionServiceImpl implements VersionService {

	@Resource
	private VersionMapper versionMapper;
	
	@Autowired
	RedisUtil redisUtil ;
	
	@Autowired
	private BaseRestrictionsService  baseRestrictionsService;
	
	@Override
	public ResponseVersion getVersionInfo(RequestVersionModel reVersion) {
		ResponseVersion resVers =null;
		if(reVersion.getType() != null && reVersion.getVersionType()!=null && !reVersion.getVersionType().isEmpty()){
			//resVers = versionMapper.getNewVersion(reVersion);
			resVers = getNewVersionForCache(reVersion.getType(),1,reVersion.getInterfaceVersion());
			if (!"".equals(reVersion.getVersionCode()) && reVersion.getVersionCode() == null) {
				return resVers;
			}
			//封装数据
			if( !StringUtils.isBlank(resVers.getVersionDescription()) ) {
				List<String> descriptions = new ArrayList<String>();
				if(resVers.getVersionDescription().indexOf(";") != -1) {
					String[] versiondesc = resVers.getVersionDescription().split(";");
					for(int i = 0 ; i < versiondesc.length ; i++) {
						descriptions.add((i + 1) + ". " + versiondesc[i]);
					}
				}else {
					descriptions.add("1. " + resVers.getVersionDescription());
				}
				resVers.setVersionDescs(descriptions);
			}
			
			Float versionCode = Float.parseFloat(reVersion.getVersionCode());
			Float minVersionCode = Float.parseFloat(resVers.getVersionMincode());
			Float latestBuildCode = Float.parseFloat(resVers.getLatestBuildCode());
			
			Float reqVersionCode = Float.parseFloat(reVersion.getVersionCode());
			// 低于最低版本
			if (versionCode < minVersionCode) {
				resVers.setVersionCode(reVersion.getVersionCode());
				resVers.setSelectUpdate(1); // 1不可选择更新
				resVers.setForcedUpdate(1); // 1必须强制更新
				return resVers;
			}
			
			// 介于最低版本和最高版本之间
			if (reqVersionCode < latestBuildCode) {
				resVers.setSelectUpdate(0); // 0可选择更新
				resVers.setForcedUpdate(0); // 0不用强制
				return resVers;
			}
			 
			// 等于最高版本
			if (reqVersionCode >= latestBuildCode) {
				resVers.setSelectUpdate(1); // 0可选择更新
				resVers.setForcedUpdate(0); // 0不用强制
				return resVers;
			}
			
 		}
		return resVers;
	}
	
	
	
public ResponseVersion getVersionInfov2(RequestVersionModel reVersion) throws Exception {
		
		ResponseVersion resVers =null;
		if(reVersion.getType() != null && reVersion.getVersionType()!=null && !reVersion.getVersionType().isEmpty()){
			resVers =  getNewVersionForCache(reVersion.getType(),1,reVersion.getInterfaceVersion());
			if (!"".equals(reVersion.getVersionCode()) && reVersion.getVersionCode() == null) {
				return resVers;
				
			}
			if(resVers == null) {
				throw new VersionNotFoundException(90012L,"数据库未配置版本信息, 接口" + reVersion.getInterfaceVersion() + " type: " + reVersion.getType());
			}
			if( !StringUtils.isBlank(resVers.getVersionDescription()) ) {
				List<String> descriptions = new ArrayList<String>();
				if(resVers.getVersionDescription().indexOf(";") != -1) {
					String[] versiondesc = resVers.getVersionDescription().split(";");
					for(int i = 0 ; i < versiondesc.length ; i++) {
						descriptions.add((i + 1) + ". " + versiondesc[i]);
					}
				}else {
					descriptions.add("1. " + resVers.getVersionDescription());
				}
				resVers.setVersionDescs(descriptions);
			}
			
			String c_versions[] = StringUtils.split(reVersion.getVersionCode(),".");
			String s_versions[] = StringUtils.split(resVers.getVersionMincode(),".");
			String s_lastversion[] = StringUtils.split(resVers.getLatestBuildCode(),".");
		    int len = c_versions.length > s_versions.length ? c_versions.length : s_versions.length;
		    if(s_lastversion != null && s_lastversion.length > 0) {
		    	len = len > s_lastversion.length ? len : s_lastversion.length;
		    }
		    
		    //下面三个循环用来补齐版本号长度，算法： 末位补0
		    String c_c_versions[] = new String[len];
		    if((len - c_versions.length) >= 0) {
		    	for(int i = 0 ; i < len ; i++) {
		    		if(i < c_versions.length) {
		    			c_c_versions[i] = c_versions[i];
		    		}else {
		    			c_c_versions[i] = "0";
		    		}
		    	}
		    }
		    String s_s_versions[] = new String[len];
		    if((len - s_versions.length) >= 0) {
		    	for(int i = 0 ; i < len ; i++) {
		    		if(i < s_versions.length) {
		    			s_s_versions[i] = s_versions[i];
		    		}else {
		    			s_s_versions[i] = "0";
		    		}
		    	}
		    }
		    String s_s_lastversion[] = new String[len];
		    if((len - s_lastversion.length) >= 0) {
		    	for(int i = 0 ; i < len ; i++) {
		    		if(i < s_lastversion.length) {
		    			s_s_lastversion[i] = s_lastversion[i];
		    		}else {
		    			s_s_lastversion[i] = "0";
		    		}
		    	}
		    }
	
		    for(int i = 0 ; i < len ; i++) {
		    	//客户端版本 小于服务端最小版本  强制更新
		    	if(Integer.parseInt(c_c_versions[i]) == Integer.parseInt(s_s_versions[i])){
		    		continue;
		    	}else if(Integer.parseInt(c_c_versions[i]) < Integer.parseInt(s_s_versions[i])) {
		    		resVers.setVersionCode(reVersion.getVersionCode());
					resVers.setSelectUpdate(0); // 1不可选择更新
					resVers.setForcedUpdate(1); // 1必须强制更新
					return resVers;
		    	}else {
		    		break;
		    	}
		    }
		    for(int i = 0 ; i < len ; i++) {
		    	// 客户端版本介于 服务端最小版本号和最大版本号之间，选择性更新
		    	if( Integer.parseInt(c_c_versions[i]) == Integer.parseInt(s_s_lastversion[i])) {
			    	if(i == (len - 1)) {//当前版本等于最新版本
		    			resVers.setSelectUpdate(1); // 不需要更新
						resVers.setForcedUpdate(0); // 0不用强制
						return resVers;
		    		}
		    		continue;
		    	}if(Integer.parseInt(c_c_versions[i]) < Integer.parseInt(s_s_lastversion[i])){
		    		resVers.setSelectUpdate(0); // 0可选择更新
					resVers.setForcedUpdate(0); // 0不用强制
					return resVers;
		    	}else {
		    		resVers.setSelectUpdate(1); // 不需要更新
					resVers.setForcedUpdate(0); // 0不用强制
					return resVers;
		    	}
		    }
		    
		    
//		    for(int i = 0 ; i < len ; i++) {
//		    	// 客户端版本大于等服务端配置的最新版本，不提示更新
//		    	if(Integer.parseInt(c_c_versions[i]) >= Integer.parseInt(s_s_lastversion[i])) {
//		    		if(i == (len - 1)) {
//		    			resVers.setSelectUpdate(1); // 0可选择更新
//						resVers.setForcedUpdate(0); // 0不用强制
//						return resVers;
//		    		}
//		    		continue;
//		    	}else if(Integer.parseInt(c_c_versions[i]) > Integer.parseInt(s_s_lastversion[i])) {
//		    		resVers.setSelectUpdate(1); // 0可选择更新
//					resVers.setForcedUpdate(0); // 0不用强制
//					return resVers;
//		    	}
//		    }
		    
		    
 		}
		
		return resVers;
	}



	public ResponseVersion getNewVersionForCache(int type,int status,String interfaceVersion) {
		int cache_timeout = this.baseRestrictionsService.getBaseRestrictionsForCache(RedisKey.VERSION_INFO_KEY_CACHE_TIME_OUT_KEY).getExperience();
		if(cache_timeout < 1) cache_timeout = RedisKey.VERSION_INFO_KEY_DEFUALT_CACHE_TIME_OUT;
		
        String cacheKey = RedisKey.VERSION_INFO_KEY + type + ":" + status + ":" + interfaceVersion ;
		String object_value = redisUtil.get(cacheKey);
		if(StringUtils.isBlank(object_value)) {
			RequestVersionModel reVersion = new RequestVersionModel();
			reVersion.setType(type);
			reVersion.setInterfaceVersion(interfaceVersion);
			ResponseVersion resVers = versionMapper.getNewVersion(reVersion);
			if(resVers != null) {
				redisUtil.set(cacheKey, JSON.toJSON(resVers).toString() , cache_timeout);
			}else {
				return null;
			}
		}
		object_value = redisUtil.get(cacheKey);
		ResponseVersion v =  JSON.parseObject(object_value, new TypeReference<ResponseVersion>() {});
		return v;
	}
	
	
}
